// pages/memberCenter/letterCenter/index.js
const {
  MemberModel
} = require('../../../utils/member-model.js');
const memberModel = new MemberModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    letters: [],
    pageIndex: 1,
    pageSize: 10,
    total: 0
  },

  getMessages() {
    memberModel.getMessages({
      merchantId: wx.getStorageSync('merchantId'),
      offset: (this.data.pageIndex - 1) * this.data.pageSize,
      limit: this.data.pageSize,
    }).then(data => {
      const messages = (data.messages || []).map((item, idx) => {
        let exchangeCode = ''
        let regx = /[^“]+(?=”)/g
        if (item.title == "捕鱼海岛礼包兑换" || item.title == "守游礼包兑换") {
          let code = item.content.match(regx) || ''
          exchangeCode = code[0] || ''
        } else {
          exchangeCode = ''
        }
        return {
          ...item,
          title: item.title,
          createAt: item.createAt,
          content: item.content,
          exchangeCode: exchangeCode || ''
        }
      })
      this.setData({
        letters: this.data.letters.concat(messages),
        total: data.total || 0
      })
      this.updateMessage(messages)
    }).catch(err => {
      if (this.data.pageIndex - 1) {
        this.setData({
          pageIndex: this.data.pageIndex - 1
        })
      }
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  updateMessage(data) {
    const merchantId = wx.getStorageSync('merchantId')
    const memberId = wx.getStorageSync('memberId')
    const unreadMsg = data.filter(item => item.messageStatus === 0).map(item => item.messageId)
    if (unreadMsg.length) {
      memberModel.updateMessage({
        merchantId,
        messageIdList: unreadMsg,
        messageStatus: 1,
        receiver: memberId
      })
    }
  },

  copy(e) {
    let code = e.currentTarget.dataset.code
    if (code) {
      wx.setClipboardData({
        data: code,
        success(res) {
          wx.getClipboardData({
            success(res) {
              wx.showToast({
                title: `兑换码复制成功`,
                icon: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getMessages()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.total > this.data.letters.length) {
      this.setData({
        pageIndex: this.data.pageIndex + 1
      }, function () {
        this.getMessages()
      })
    }
  }
})